<template>
  <div>
    <el-dialog
      ref="dialog"
      model-value
      custom-class="dialog-form"
      close-on-click-modal
      append-to-body
      draggable
      v-bind="$attrs"
    >
      <slot />
      <template #footer v-if="visibleFooter">
        <slot name="footer">
          <div class="dialog-footer">
            <!-- <el-button @click="handleCancel">取消</el-button> -->
            <el-button type="primary" :loading="confirmLoading" v-debounce="[handleConfirm]">
              确定
            </el-button>
          </div>
        </slot>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, PropType, useSlots, computed } from 'vue'
import type { IElDialog } from '@/types/element-plus'

const props = defineProps({
  // 控制显示footer
  visibleFooter: {
    type: Boolean,
    default: undefined
  },
  confirm: {
    type: Function as PropType<() => Promise<void>>,
    default: () => Promise.resolve()
  }
})

const visibleFooter = computed(() => {
  if (typeof props.visibleFooter === 'boolean') return props.visibleFooter
  const slot: any = useSlots()
  if (slot.footer) return true
  const defaultSlot = slot.default()
  const formEl = defaultSlot.find((t: any) => t.type.name === 'ElForm')
  const formProps = formEl ? formEl.props : null
  if (!formProps || formProps.disabled === '') return false
  return !formProps.disabled
})
const dialog = ref<IElDialog>()
const confirmLoading = ref(false)

// 取消
// const handleCancel = () => {
//   if (dialog.value) {
//     dialog.value.visible = false
//   }
// }

// 确定
const handleConfirm = async () => {
  confirmLoading.value = true
  await props.confirm().finally(() => {
    confirmLoading.value = false
  })
}
</script>
<script lang="ts">
export default {
  inheritAttrs: false
}
</script>

<style lang="scss">
.dialog-form {
  border-radius: 5px;
  overflow: hidden;
  .el-dialog__header {
    background: var(--html-bg-color);
    margin-right: 0;
  }
  .el-dialog__title {
    font-size: 24px;
    font-weight: 700;
  }
  .el-dialog__footer {
    padding: 0;
  }
  .dialog-footer {
    padding: var(--el-dialog-padding-primary);
    padding-top: 10px;
    background-color: var(--html-bg-color);
  }
}
</style>
